import fs from "node:fs"
import path from "node:path"
import http from "node:http"
import { fileURLToPath } from "node:url"
const __dirname = path.dirname(fileURLToPath(import.meta.url))
console.log("__dirname: ", __dirname)
function parseFile(data, separator) {
    // 利用分隔符分割data
    const bufArr = split(data, separator).slice(1, -1)
    bufArr.forEach(item => {
        const [head, body] = split(item, "\r\n\r\n");
        // 可能存在两行head，所以用换行符\r\n分割下
        // 这里的第一个元素是截取后剩下空buffer，所以要剔除掉
        const headArr = split(head, "\r\n").slice(1)
        console.log("headArr: ", headArr)
        // head的第一行肯定是Content-Disposition
        // 通过这个字段肯定能拿到文件名
        // 通过parseHeader解析head
        const headerVal = parseHeader(headArr[0].toString())
        console.log("headerVal: ",headerVal, Object.prototype.toString.call(headerVal),headerVal.filename)
        // 如果head内存在filename字段，则代表是一个文件
        if (headerVal.filename) {
            const url = path.resolve(__dirname, `./public/${headerVal.filename}`);
            console.log("url: ", url)
            // 写入文件到磁盘
            fs.writeFile(url, body.slice(0, -2), err => {
                if (err) {
                    console.error(err)
                }
            })
        }
    })
}
function parseHeader(header) {
    const [name, value] = header.split(":");
    console.log(name, value);
    const valueObj = {};
    value.split("; ").forEach(item => {
        const [key, val = ""] = item.split("=")
        valueObj[key] = val && JSON.parse(val)
    })
    return valueObj
}
function split(buffer, separator) {
    const res = [];
    let offset = 0;
    let index = buffer.indexOf(separator, 0)
    while (index !== -1) {
        res.push(buffer.slice(offset, index));
        offset = index + separator.length;
        index = buffer.indexOf(separator,index + separator.length)
    }
    res.push(buffer.slice(offset))
    return res;
}
// 创建一个服务器
const server = http.createServer((req, res) => {
    console.log(req.headers);
    res.setHeader("Access-Control-Allow-Headers", "Content-Type");
    res.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,PUT,DELETE");
    // res.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
    // res.setHeader("Access-Control-Allow-Origin", "*");

    if (req.headers.origin.includes("localhost")) {
        res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
    }
    if (req.url === "/file") {
        // 创建一个0字节的内存，用来存储请求体的内容
        let data = Buffer.alloc(0);
        // req是一个可读流
        req.on("data", chunk => {
            data = Buffer.concat([data, chunk]);
        })
        req.on("end", () => {
            // 拿到请求头中的分割符
            // 在请求体中的分隔符会多两个 --
            console.log(req.headers["content-type"]);
            const separator = `--${req.headers["content-type"].split("boundary=")[1]}`
            // 解析文件
            parseFile(data, separator);
            res.end();
        })
    } else {
        res.setHeader("Content-Type", "application/javascript");
        fs.createReadStream(path.resolve(__dirname, "." + req.url)).pipe(res);
    }
})
server.listen(3000, "192.168.2.6", () => {
    console.log("server start up 3000")
})
/**
 * 进入目录
 * 双击start-server.cmd
 * 即执行node index.mjs
 */